<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物料编号">
              <el-input v-model="queryParams.equipmentMaterialId" placeholder="请输入物料编号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料名称">
              <el-input v-model="queryParams.equipmentMaterialName" placeholder="请输入物料名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料类别">
              <el-select v-model="queryParams.materialCategory" placeholder="请选择物料类别" clearable>
                <el-option v-for="item in materialCategoryOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增物料
      </el-button>
      <el-table :data="materialList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="equipmentMaterialId" label="物料编号" width="180" align="center" />
        <el-table-column prop="equipmentMaterialName" label="物料名称"  align="center" />
        <el-table-column prop="materialCategory" label="物料类别" align="center">
          <template #default="{ row }">
            {{ getMaterialCategoryLabel(row.materialCategory) }}
          </template>
        </el-table-column>
        <el-table-column prop="specificationModel" label="规格型号" align="center" />
        <el-table-column prop="inventoryQuantity" label="库存数量"  align="center" />
        <el-table-column prop="safetyStockValue" label="安全库存"  align="center" />
        <el-table-column prop="purchasePrice" label="采购价格" align="center">
          <template #default="{ row }">
            {{ row.purchasePrice ? `¥${row.purchasePrice}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="manufacturer" label="生产厂家" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物料编号" prop="equipmentMaterialId">
          <el-input v-model="form.equipmentMaterialId" placeholder="请输入物料编号" />
        </el-form-item>
        <el-form-item label="物料名称" prop="equipmentMaterialName">
          <el-input v-model="form.equipmentMaterialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料类别" prop="materialCategory">
          <el-select v-model="form.materialCategory" placeholder="请选择物料类别" style="width: 100%">
            <el-option v-for="item in materialCategoryOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="specificationModel">
          <el-input v-model="form.specificationModel" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="库存数量" prop="inventoryQuantity">
          <el-input-number v-model="form.inventoryQuantity" :min="0" :precision="0" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="安全库存" prop="safetyStockValue">
          <el-input-number v-model="form.safetyStockValue" :min="0" :precision="0" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="采购价格" prop="purchasePrice">
          <el-input-number v-model="form.purchasePrice" :min="0" :precision="2" controls-position="right"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="生产日期">
          <el-date-picker v-model="form.productionDate" type="date" placeholder="选择生产日期" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="保质期">
          <el-date-picker v-model="form.expirationDate" type="date" placeholder="选择保质期" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商联系方式">
          <el-input v-model="form.supplierContact" placeholder="请输入供应商联系方式" />
        </el-form-item>
        <el-form-item label="供应合同编号">
          <el-input v-model="form.supplyContractNumber" placeholder="请输入供应合同编号" />
        </el-form-item>
        <el-form-item label="上次采购时间">
          <el-date-picker v-model="form.lastPurchaseTime" type="datetime" placeholder="选择上次采购时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="预计下次采购时间">
          <el-date-picker v-model="form.expectedNextPurchaseTime" type="datetime" placeholder="选择预计下次采购时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="申购状态">
          <el-select v-model="form.equipmentPurchaseApplicationStatus" placeholder="请选择申购状态" style="width: 100%">
            <el-option label="未申请" value="未申请" />
            <el-option label="申请中" value="申请中" />
            <el-option label="已批准" value="已批准" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>
        </el-form-item>
        <el-form-item label="申购时间">
          <el-date-picker v-model="form.equipmentPurchaseApplicationTime" type="datetime" placeholder="选择申购时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="申购原因">
          <el-input v-model="form.equipmentPurchaseApplicationReason" type="textarea" :rows="2" placeholder="请输入申购原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`物料详情 - ${detailDialog.data.equipmentMaterialName}`"
      width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="物料编号">{{ detailDialog.data.equipmentMaterialId }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ detailDialog.data.equipmentMaterialName }}</el-descriptions-item>
        <el-descriptions-item label="物料类别">{{ getMaterialCategoryLabel(detailDialog.data.materialCategory)
        }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detailDialog.data.specificationModel }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">{{ detailDialog.data.inventoryQuantity }}</el-descriptions-item>
        <el-descriptions-item label="安全库存">{{ detailDialog.data.safetyStockValue }}</el-descriptions-item>
        <el-descriptions-item label="采购价格">{{ detailDialog.data.purchasePrice ? `¥${detailDialog.data.purchasePrice}` :
          '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">{{ detailDialog.data.manufacturer }}</el-descriptions-item>
        <el-descriptions-item label="生产日期">{{ detailDialog.data.productionDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="保质期">{{ detailDialog.data.expirationDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ detailDialog.data.supplierName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="供应商联系方式">{{ detailDialog.data.supplierContact || '-' }}</el-descriptions-item>
        <el-descriptions-item label="供应合同编号">{{ detailDialog.data.supplyContractNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="上次采购时间">{{ detailDialog.data.lastPurchaseTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="预计下次采购时间">{{ detailDialog.data.expectedNextPurchaseTime || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="申购状态">{{ detailDialog.data.equipmentPurchaseApplicationStatus || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="申购时间">{{ detailDialog.data.equipmentPurchaseApplicationTime || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="申购原因">
          <pre class="pre-formatted">{{ detailDialog.data.equipmentPurchaseApplicationReason || '无' }}</pre>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listEquipmentMaterial,
  getMaterialCategoryList,
  getEquipmentMaterialDetail,
  addEquipmentMaterial,
  updateEquipmentMaterial,
  deleteEquipmentMaterial
} from '@/api/prod_operate/device/warehouse/supplies'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  equipmentMaterialId: '',
  equipmentMaterialName: '',
  materialCategory: ''
})

// 表单数据
const form = reactive({
  id: undefined,
  equipmentMaterialId: '',
  equipmentMaterialName: '',
  materialCategory: '',
  specificationModel: '',
  inventoryQuantity: 0,
  safetyStockValue: 0,
  purchasePrice: 0,
  manufacturer: '',
  productionDate: '',
  expirationDate: '',
  supplierName: '',
  supplierContact: '',
  supplyContractNumber: '',
  lastPurchaseTime: '',
  expectedNextPurchaseTime: '',
  equipmentPurchaseApplicationStatus: '',
  equipmentPurchaseApplicationTime: '',
  equipmentPurchaseApplicationReason: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 下拉选项数据
const materialCategoryOptions = ref([])

// 表格数据
const materialList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()

// 表单验证规则
const rules = reactive({
  equipmentMaterialId: [
    { required: true, message: '请输入物料编号', trigger: 'blur' }
  ],
  equipmentMaterialName: [
    { required: true, message: '请输入物料名称', trigger: 'blur' }
  ],
  materialCategory: [
    { required: true, message: '请选择物料类别', trigger: 'change' }
  ],
  specificationModel: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  inventoryQuantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  safetyStockValue: [
    { required: true, message: '请输入安全库存', trigger: 'blur' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购价格', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ]
})

// 获取物料类别标签
const getMaterialCategoryLabel = (value) => {
  const item = materialCategoryOptions.value.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const res = await getMaterialCategoryList()
    materialCategoryOptions.value = res.data || []
  } catch (error) {
    console.error('获取物料类别列表失败:', error)
    ElMessage.error('获取物料类别列表失败')
  }
}

// 获取设备物料列表
const fetchMaterialList = async () => {
  try {
    loading.value = true
    const res = await listEquipmentMaterial(queryParams)
    materialList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取设备物料列表失败:', error)
    ElMessage.error('获取设备物料列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchMaterialList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.equipmentMaterialId = ''
  queryParams.equipmentMaterialName = ''
  queryParams.materialCategory = ''
  fetchMaterialList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchMaterialList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchMaterialList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增物料'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    id: undefined,
    equipmentMaterialId: '',
    equipmentMaterialName: '',
    materialCategory: '',
    specificationModel: '',
    inventoryQuantity: 0,
    safetyStockValue: 0,
    purchasePrice: 0,
    manufacturer: '',
    productionDate: '',
    expirationDate: '',
    supplierName: '',
    supplierContact: '',
    supplyContractNumber: '',
    lastPurchaseTime: '',
    expectedNextPurchaseTime: '',
    equipmentPurchaseApplicationStatus: '',
    equipmentPurchaseApplicationTime: '',
    equipmentPurchaseApplicationReason: ''
  })
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getEquipmentMaterialDetail(row.id)
    Object.assign(form, res.data)
    dialog.visible = true
    dialog.title = '编辑物料'
  } catch (error) {
    console.error('获取设备物料详情失败:', error)
    ElMessage.error('获取设备物料详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getEquipmentMaterialDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取设备物料详情失败:', error)
    ElMessage.error('获取设备物料详情失败')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除物料 "${row.equipmentMaterialName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteEquipmentMaterial(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchMaterialList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const isAdd = form.id === undefined
    const api = isAdd ? addEquipmentMaterial : updateEquipmentMaterial

    await api(form)
    ElMessage.success('操作成功')
    dialog.visible = false
    fetchMaterialList()
  } catch (error) {
    console.error('保存设备物料失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchMaterialList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>